import random
import time

from django import http
from django.shortcuts import render
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
# Create your views here.
from django.views import View
from tasks.sms import send_sms
from utils.response_code import RET, error_map
from verifications import constants


class ImageCodeView(View):
    def get(self, request, uuid):
        # 1, 通过 captcha模块 获取 图片和图片文本内容
        text, img = captcha.generate_captcha()

        # 2, 保存图片内容到redis
        # 保存图片验证码
        redis_conn = get_redis_connection('verify_code')  # settings  CACHES  里面的配置名字
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_EXPIRY, text)

        # 3, 返回图片给前端
        return http.HttpResponse(img, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 1,初始化数据 mobile, image_code, uuid
        image_code = request.GET.get('image_code').upper()
        image_code_id = request.GET.get('image_code_id')

        # 1,2 校验数据
        if not all([image_code, image_code_id]):
            return http.JsonResponse({'code':RET.PARAMERR,'errmsg':error_map[RET.PARAMERR]})

        redis_conn = get_redis_connection('verify_code')

        redis_image_code = redis_conn.get('img_%s' % image_code_id)
        if redis_image_code:
            redis_image_code = redis_image_code.decode()

        if image_code != redis_image_code:
            return http.JsonResponse({'code':RET.IMAGECODEERR,'errmsg': '图片验证码不正确'})

        # # 补充 判断是否发送中
        redis_sms_flag = redis_conn.get('sms_flag_%s' % mobile)  # b'sending'

        if redis_sms_flag:
            return http.JsonResponse({'code':RET.REQERR,'errmsg': '不能频繁请求短信'})

        # 2,处理业务逻辑
        # 获取随机短信验证码
        sms_code = '%04d' % random.randint(0, 9999)
        # 保持验证码到redis中
        pl = redis_conn.pipeline()
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # redis_conn.setex('sms_flag_%s' % mobile, 60, 'sending')
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRY, sms_code)
        pl.setex('sms_flag_%s' % mobile, constants.SMS_CODE_REQ_LIMIT_TIME, 'sending')
        pl.execute()

        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)

        # 延时
        # time.sleep(5)
        # 异步调用celery的发送短信任务
        # send_sms.delay(mobile, sms_code, 5, 1)
        print('sms_code:%s' % sms_code)

        # 3,返回响应
        res = {
            'code': RET.OK,
            'errmsg': 'success'
        }
        return http.JsonResponse(res)
        pass
